package com.nervenets.shopping.controller.common.params;

import com.nervenets.general.aspect.validate.NotUrl;
import com.nervenets.general.exception.LogicException;
import com.nervenets.general.web.params.FormParams;
import com.nervenets.shopping.hibernate.domain.common.Certificate;
import com.nervenets.shopping.service.CertificateService;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;

@EqualsAndHashCode(callSuper = true)
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class CertificateFormParams extends FormParams<Certificate, CertificateService> {
    @ApiModelProperty(value = "关联人ID", required = true)
    @Positive
    private long unionId;
    @ApiModelProperty(value = "获得时间", required = true)
    @Positive
    private long getTime;
    @ApiModelProperty(value = "证书名称", required = true)
    @NotBlank
    private String name;
    @ApiModelProperty(value = "证书编号", required = true)
    @NotBlank
    private String number;
    @ApiModelProperty(value = "证书照片", required = true)
    @NotUrl
    private String image;

    @Override
    public Certificate validateAndBuild(CertificateService service, HttpServletRequest request, HttpServletResponse response) {
        Certificate certificate = super.validateAndBuild(service, request, response);
        if (service.hasUniqueKey(certificate.getId(), (predicates, root, criteriaQuery, criteriaBuilder) -> {
            predicates.add(criteriaBuilder.equal(root.get("unionId"), certificate.getUnionId()));
            predicates.add(criteriaBuilder.equal(root.get("name"), certificate.getName()));
        })) {
            throw new LogicException(String.format("已存在【%s】的证书信息", certificate.getName()));
        }
        return certificate;
    }
}
